package cn.hxzy.student.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hxzy.common.domain.Task;
import cn.hxzy.common.domain.TaskManager;
import cn.hxzy.common.domain.vo.TaskSave;
import cn.hxzy.common.domain.vo.TaskVo;
import cn.hxzy.common.response.R;
import cn.hxzy.common.response.StatusEnum;
import cn.hxzy.course.service.TaskService;
import cn.hxzy.student.service.TaskManagerService;
import cn.hxzy.common.util.AliOssUtil;
import cn.hxzy.common.util.ThreadLocalUtil;
import cn.hxzy.user.service.impl.UserServiceImpl;
import com.aliyun.oss.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {


    @Autowired
    private TaskManagerService taskManagerService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserServiceImpl userService;


    /**
     * 提交作业
     *
     * @param taskManager 作业详细信息实体类
     * @return
     */
    @PostMapping("/uptask")
    public R uptask(@RequestBody TaskManager taskManager) {
        Long userId = ThreadLocalUtil.getUser().getUserId();
        int i1 = userId.intValue();
        Integer i2 = Integer.valueOf(i1);
        //获取提交次数
        Integer count = taskManagerService.count(i2, taskManager.getTaskId());
        taskManager.setStudentId(i2);
        //提交时间
        taskManager.setSubmitTime(LocalDateTime.now());
        taskManager.setCommit(0);
        boolean b = false;
        //判断是否是第一次提交
        if (count == null) {
            //提交作业
            b = taskManagerService.save(taskManager);
        } else {
            //修改作业
            b = taskManagerService.updateTaskManger(taskManager);
        }
        if (b) {
            return R.success(b);
        }
        return R.error(StatusEnum.PARAM_INVALID);
    }

    /**
     * 根据作业id与学生编号查询作业详情
     *
     * @param taskId
     * @return
     */
    @GetMapping("/selectTaskManagerByTaskId/{taskId}")
    public R selectTaskManagerByTaskId(@PathVariable("taskId") Integer taskId) {
        TaskManager taskManager = taskManagerService.getTaskMangerByTaskId(taskId);
        if (taskManager == null){
            return R.success(0);
        }
        return R.success(taskManager);
    }

    /**
     * 修改提交状态
     * @param id
     * @return
     */
    @PostMapping("/updateCommit/{id}")
    public R updateCommit(@PathVariable("id") Integer id) {
        TaskManager taskManager = taskManagerService.getById(id);
        taskManager.setCommit(1);
        boolean b = taskManagerService.updateById(taskManager);
        if (b) {
            return R.success(b);
        }
        return R.error(StatusEnum.PARAM_INVALID);
    }



    //提交作业 图片、附件返回地址
    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") List<MultipartFile> file) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        for (MultipartFile multipartFile : file) {
            //原始的文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //新命名文件名称
            String url = AliOssUtil.uploadFile(originalFilename, multipartFile.getInputStream());
            if (StringUtils.isNullOrEmpty(url)) {
                return R.error(StatusEnum.PARAM_INVALID);
            }
            stringBuffer.append(url+",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        String url = stringBuffer.toString();
        return R.success(url);
    }

    //富文本图片上传回传
    @PostMapping("/upload01")
    public R<Map> upload01(@RequestParam("file") List<MultipartFile> file) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        for (MultipartFile multipartFile : file) {
            //原始的文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //新命名文件名称
            String url = AliOssUtil.uploadFile(originalFilename, multipartFile.getInputStream());
            if (StringUtils.isNullOrEmpty(url)) {
                return R.error(StatusEnum.PARAM_INVALID);
            }
            stringBuffer.append(url+",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        String url = stringBuffer.toString();
        Map<String, Object> resMap = new HashMap<>();
        // wangEditor上传图片成功后， 需要返回的参数
        resMap.put("errno", 0);
        resMap.put("data", CollUtil.newArrayList(Dict.create().set("url", url)));
        return R.success(resMap);
    }

    //富文本附件上传回传
    @PostMapping("/upload02")
    public R<Map> upload02(@RequestParam("file") List<MultipartFile> files) throws Exception {
        List<Map<String, String>> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            // 原始的文件名
            String originalFilename = file.getOriginalFilename();
            // 新命名文件名称
            String url = AliOssUtil.uploadFile(originalFilename, file.getInputStream());
            if (StringUtils.isNullOrEmpty(url)) {
                return R.error(StatusEnum.PARAM_INVALID);
            }
            Map<String, String> fileData = new HashMap<>();
            fileData.put("url", url);

            fileData.put("name", originalFilename);

            urls.add(fileData);
        }
        Map<String, Object> resMap = new HashMap<>();
        // wangEditor 上传成功后，需要返回的参数
        resMap.put("errno", 0);
        resMap.put("data", urls);
        return R.success(resMap);
    }

    /**
     * 添加到redis
     * @param taskSave
     * @return
     */
    @PostMapping("/insertTaskRedis")
    public R insertTaskRedis(@RequestBody TaskSave taskSave) {
       Long userId = ThreadLocalUtil.getUser().getUserId();
        int i1 = userId.intValue();
        Integer stu = Integer.valueOf(i1);
        taskSave.setStudentId(stu);
        //获取学生编号
        //获取作业信息
        TaskManager taskManger = taskManagerService.getTaskMangerByTaskId(taskSave.getTaskId());
        //判断作业是否存在
        if (taskManger != null){
            //设置作业内容
            taskManger.setTaskTxt(taskSave.getTaskInfo());
            boolean b = taskManagerService.updateById(taskManger);
            if (b){
                //删除redis集合
                List<Object> range = redisTemplate.opsForList().range(taskSave.getStudentId().toString(), 0, -1);
                //遍历集合
                for (int i = 0; i < range.size(); i++) {
                    //取集合元素
                    TaskSave index = (TaskSave) redisTemplate.opsForList().index(taskSave.getTaskId().toString(), i);
                    if (index.getTaskId() == taskManger.getTaskId()){
                        //删除集合元素
                        redisTemplate.opsForList().remove(taskSave.getTaskId().toString(), i, index);
                    }
                }
                return R.success("保存成功");
            }
            return R.error(StatusEnum.PARAM_INVALID);
        }
        //判断操作是否成功
        boolean bool=false;
        //判断redis是否存在
        List<Object> taskList = redisTemplate.opsForList().range(taskSave.getStudentId().toString(), 0, -1);
        //判断集合是否为空,为空则说明当前无键为studentId的集合
        if (ObjectUtils.isEmpty(taskList)) {
            //添加到redis
            redisTemplate.opsForList().rightPush(taskSave.getStudentId().toString(), taskSave);
            bool=true;
        }else {
            //遍历取到的集合
            for (int i = 0; i < taskList.size(); i++) {
                //取到当前的集合元素
                TaskSave index = (TaskSave) redisTemplate.opsForList().index(taskSave.getStudentId().toString(), i);
                //判断当前集合元素是否和传过来的元素相等
                if (index.getTaskId()==taskSave.getTaskId()){
                    //替换对象
                    redisTemplate.opsForList().set(taskSave.getStudentId().toString(),i,taskSave);
                    bool=true;
                }else {
                    //添加对象
                    redisTemplate.opsForList().rightPush(taskSave.getStudentId().toString(),taskSave);
                    bool=true;
                }
            }
        }
        //判断是否添加成功
        if (bool){
            return R.success("保存成功");
        }
        //判断是否添加成功
        return R.error(StatusEnum.PARAM_INVALID);
    }

    /**
     * 获取保存的redis集合
     * @param taskId
     * @return
     */
    @GetMapping("/getTaskRedis/{taskId}")
    public R<TaskSave> getTaskRedis(@PathVariable("taskId") Integer taskId){
        Long userId = ThreadLocalUtil.getUser().getUserId();
        //获取redis集合
        List<Object> range = redisTemplate.opsForList().range(userId.toString(), 0, -1);
        //遍历集合
        for (int i = 0; i < range.size(); i++) {
            //取集合元素
            TaskSave index = (TaskSave) redisTemplate.opsForList().index(userId.toString(), i);
            if (index.getTaskId()==taskId){
                return R.success(index);
            }
        }
        return R.success(new TaskSave());
    }

    //查询作业详情
    @GetMapping("/getTaskInfo/{taskId}")
    public R<Map> getTaskInfo(@PathVariable("taskId") Integer taskId) {
        //查询作业名称和小结名称
        Map map = taskService.selectTaskById(taskId);
        //查询学生作业内容
        TaskManager taskManger = taskManagerService.getTaskMangerByTaskId(taskId);
        if(taskManger!=null && taskManger.getTeacherId()!=null){
            map.put("teacherName",userService.getById(taskManger.getTeacherId()).getNickName());
        }else{
            map.put("teacherName",null);
        }
        map.put("taskManger",taskManger);
        return R.success(map);

    }

    //提交作业
    @PostMapping("/submit")
    public R submit(@RequestBody Map map) {
        //这里要是用户id传过来是空的的话就走学生上传作业反之就是修改作业
        if(map.get("studentId")==null){
            return R.success(taskService.insertTask(map));
        }else {
            return R.success(taskService.updateTaskManger(map));
        }

    }
}
